<template>
  <div class="roles">
    <!-- 面包屑导航 -->
    <breadcrumb :breadcrumb="breadcrumb"></breadcrumb>
    <!-- 内容卡片区 -->
    <el-card class="box-card content">
      <!-- 添加 -->
      <el-button class="addroles" @click="addRoles" type="primary">添加角色</el-button>
      <!-- 列表 -->
      <el-table :data="rolesList" style="width: 100%" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['tagbutBor','tagCenter',index1===0?'tagTopBor':'']"
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="4">
                <el-tag
                  @close="delRolesAuthority(scope.row,item1.id)"
                  closable
                  type="success"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">
                <!-- 二级权限 -->
                <el-row
                  :class="[index2===item1.children.length-1?'':'tagbutBor','tagCenter']"
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="4">
                    <el-tag
                      @close="delRolesAuthority(scope.row,item2.id)"
                      closable
                      type="info"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="20">
                    <!-- 三级权限-->
                    <el-tag
                      @close="delRolesAuthority(scope.row,item3.id)"
                      type="warning"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="address" label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="editRoles(scope.row)"
              type="primary"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              size="mini"
              @click="delRole(scope.row)"
              type="danger"
              icon="el-icon-delete"
            >删除</el-button>
            <el-button
              @click="showSetRightDialog(scope.row)"
              size="mini"
              type="warning"
              icon="el-icon-setting"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑角色弹框 -->
      <el-dialog
        :title="title+'角色'"
        :visible.sync="addOreditDialogVisible"
        width="50%"
        @close="clearData('rulesForm')"
      >
        <el-form
          :model="rulesForm"
          :rules="rules"
          ref="rulesForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rulesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rulesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addOreditDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOrEditFun">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限弹框 -->
      <el-dialog
        class="roles"
        @close="clearDefKeys"
        title="分配权限"
        :visible.sync="dialogVisible"
        width="40%"
      >
        <el-tree
          :data="rightsList"
          show-checkbox
          node-key="id"
          :default-checked-keys="defKeys"
          :default-expanded-keys="defKeys"
          :props="treeProps"
          ref="treeRef"
          :check-on-click-node="true"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
           
<script>
export default {
  name: "roles",
  data() {
    return {
      // 面包屑导航传值
      breadcrumb: ["权限管理", "角色列表"],
      // 角色列表
      rolesList: [],
      // 所有权限列表
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        //通过label设置树形节点文本展示authName
        label: "authName",
        //设置通过children属性展示子节点信息
        children: "children"
      },
      // 角色已有的权限---用于树形控件默认展开项
      defKeys: [],
      // 分配权限弹框
      dialogVisible: false,
      // 所需要的用的角色的id值、
      roleId: 0,
      // 添加/编辑角色弹框---标题
      title: "",
      // 添加/编辑角色弹框---影藏或显示
      addOreditDialogVisible: false,
      // 添加/编辑角色弹框---输入内容
      rulesForm: {
        roleName: "",
        roleDesc: ""
      },
      rules: {
        roleName: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ]
      }
    };
  },
  // 生命周期函数
  created() {
    this.getRoles();
  },
  methods: {
    // 初始化
    async getRoles() {
      const { data: res } = await this.$http.get(`/roles`);
      if (res.meta.status == 200) {
        this.$message({
          message: res.meta.msg || "获取列表成功",
          type: "success"
        });
        this.rolesList = res.data;
      }
    },
    // 添加角色
    addRoles() {
      this.title = "添加";
      // 显示弹框;
      this.addOreditDialogVisible = true;
    },
    // 编辑角色
    editRoles(row) {
      const { id, roleName, roleDesc } = row;
      this.roleId = id;
      this.rulesForm.roleName = roleName;
      this.rulesForm.roleDesc = roleDesc;
      this.title = "编辑";
      // 显示弹框;
      this.addOreditDialogVisible = true;
    },
    // 删除角色
    delRole(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${row.id}`);
         
          if (res.meta.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getRoles();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 添加或编辑角色的请求处理
    addOrEditFun() {
      this.$refs.rulesForm.validate(async valid => {
        if (valid) {
          if (this.title == "添加") {
            let { data: res } = await this.$http.post("/roles", this.rulesForm);
            if (res.meta.status == 201) {
              this.$message({
                type: "success",
                message: res.meta.msg
              });
              this.getRoles();
              this.addOreditDialogVisible = false;
            }
          } else if (this.title == "编辑") {
            let { data: res } = await this.$http.put(
              `roles/${this.roleId}`,
              this.rulesForm
            );
            if (res.meta.status == 200) {
              this.$message({
                type: "success",
                message: res.meta.msg
              });
              this.getRoles();
              this.addOreditDialogVisible = false;
            }
          } else {
            return false;
          }
        } else {
          this.$message.error('输入内容为空！')
          return false;
        }
      });
    },
    // 清除数据
    clearData(name) {
      this.roleId = 0;
      this.$refs[name].resetFields();
      this.title = "";
    },
    // 删除指定权限
    delRolesAuthority(role, rightId) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          role.children = res.data;
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //显示分配权限弹框====加载权限列表和已有权限
    async showSetRightDialog(role) {
      // 保存角色的id值
      this.roleId = role.id;
      this.dialogVisible = true;
      const { data: res } = await this.$http.get(`/rights/tree`);
      // 调用递归函数--获取用户已有权限
      this.getLeafKeys(role, this.defKeys);
      // 渲染权限列表
      this.rightsList = res.data;
    },
    // 获取用户已有的全权限---递归函数来获取
    getLeafKeys(node, arr) {
      // 判读是否有children属性
      if (!node.children) return arr.push(node.id);
      // 递归调用
      node.children.forEach(element => this.getLeafKeys(element, arr));
    },
    // 为用户分配权限
    async allotRights() {
      // 获取树形控件中，选中和半选中的权限id
      // 选中--三级权限getCheckedNodes();
      // 半选中---一级和二级getHalfCheckedNodes;
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: keys.join(",")
        }
      );
      if (res.meta.status == 200) {
        this.$message({
          message: res.meta.msg || "设置权限成功",
          type: "success"
        });
        // 初始化
        this.getRoles();
        // 关闭弹框
        this.dialogVisible = false;
      }
    },
    clearDefKeys() {
      this.defKeys = [];
      this.roleId = 0;
    }
  }
};
</script>
<style scoped lang='less'>
.roles {
  width: 100%;
  height: 100%;
  .content {
    margin-top: 10px;
    padding: 10px 20px;
    background-color: #fff;
    margin-top: 20px;
    border-radius: 8px;
    .addroles {
      margin-bottom: 10px;
    }
    /deep/ .roles {
      .el-dialog__body {
        max-height: 350px;
        overflow: auto;
      }
    }
  }
  // 展开权限 ==居中
  .tagCenter {
    display: flex;
    align-items: center;

    .el-tag {
      margin: 10px;
    }
  }
  // 展开权限 ==上边框
  .tagTopBor {
    border-top: 1px solid #eee;
  }
  // 展开权限 ==下边框
  .tagbutBor {
    border-bottom: 1px solid #eee;
  }
}
</style>